package org.example.guavalearn.bloomfilter;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;

import java.nio.charset.Charset;

@SuppressWarnings("UnstableApiUsage")
class CachedCrawler implements Crawler {

    private final BloomFilter<String> existsFilter;
    private final Crawler crawler;

    CachedCrawler(Crawler crawler, long expectedInsertions, double fpp) {
        this.existsFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, fpp);
        this.crawler = crawler;
    }

    @Override
    public void put(String key) {
        crawler.put(key);
        existsFilter.put(key);
    }

    @Override
    public boolean contains(String key) {
        if (!existsFilter.mightContain(key)) {
            return false;
        }
        return crawler.contains(key);
    }

    @Override
    public String test(String key) {
        if (!existsFilter.mightContain(key)) {
            return "false (cached)";
        }
        return String.valueOf(crawler.contains(key));
    }
}
